{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "40d3d3b6",
   "metadata": {},
   "source": [
    "# 1. 语音识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "58be03ef",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Request time cost 0.275403\n",
      "{\"corpus_no\":\"7230642822020339895\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"北京科技馆。\"],\"sn\":\"11971651461683515222\"}\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# coding=utf-8\n",
    "\n",
    "import sys\n",
    "import json\n",
    "import base64\n",
    "import time\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "    timer = time.perf_counter\n",
    "else:\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "    if sys.platform == \"win32\":\n",
    "        timer = time.clock\n",
    "    else:\n",
    "        # On most other platforms the best timer is time.time()\n",
    "        timer = time.time\n",
    "\n",
    "API_KEY = 'smxkOHWjqLVljEmIry5vuSYI'\n",
    "SECRET_KEY = 'ky3FZeSSDurxLyLLqZ2kPaEnts9NH1W1'\n",
    "\n",
    "# 需要识别的文件\n",
    "AUDIO_FILE = 'speech-demo-master/rest-api-asr/python/audio/16k.m4a'  # 只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "# 文件格式\n",
    "FORMAT = AUDIO_FILE[-3:]  # 文件后缀只支持 pcm/wav/amr 格式，极速版额外支持m4a 格式\n",
    "\n",
    "CUID = '123456PYTHON'\n",
    "# 采样率\n",
    "RATE = 16000  # 固定值\n",
    "\n",
    "# 普通版\n",
    "\n",
    "DEV_PID = 1537  # 1537 表示识别普通话，使用输入法模型。根据文档填写PID，选择语言及识别模型\n",
    "ASR_URL = 'http://vop.baidu.com/server_api'\n",
    "SCOPE = 'audio_voice_assistant_get'  # 有此scope表示有asr能力，没有请在网页里勾选，非常旧的应用可能没有\n",
    "\n",
    "#测试自训练平台需要打开以下信息， 自训练平台模型上线后，您会看见 第二步：“”获取专属模型参数pid:8001，modelid:1234”，按照这个信息获取 dev_pid=8001，lm_id=1234\n",
    "# DEV_PID = 8001 ;   \n",
    "# LM_ID = 1234 ;\n",
    "\n",
    "# 极速版 打开注释的话请填写自己申请的appkey appSecret ，并在网页中开通极速版（开通后可能会收费）\n",
    "\n",
    "# DEV_PID = 80001\n",
    "# ASR_URL = 'http://vop.baidu.com/pro_api'\n",
    "# SCOPE = 'brain_enhanced_asr'  # 有此scope表示有极速版能力，没有请在网页里开通极速版\n",
    "\n",
    "# 忽略scope检查，非常旧的应用可能没有\n",
    "# SCOPE = False\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'\n",
    "\n",
    "\n",
    "def fetch_token():\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode( 'utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "#         print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str =  result_str.decode()\n",
    "\n",
    "#     print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "#     print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "#         print(SCOPE)\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "#         print('SUCCESS WITH TOKEN: %s  EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    token = fetch_token()\n",
    "\n",
    "    speech_data = []\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "\n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "    speech = base64.b64encode(speech_data)\n",
    "    if (IS_PY3):\n",
    "        speech = str(speech, 'utf-8')\n",
    "    params = {'dev_pid': DEV_PID,\n",
    "             #\"lm_id\" : LM_ID,    #测试自训练平台开启此项\n",
    "              'format': FORMAT,\n",
    "              'rate': RATE,\n",
    "              'token': token,\n",
    "              'cuid': CUID,\n",
    "              'channel': 1,\n",
    "              'speech': speech,\n",
    "              'len': length\n",
    "              }\n",
    "    post_data = json.dumps(params, sort_keys=False)\n",
    "    # print post_data\n",
    "    req = Request(ASR_URL, post_data.encode('utf-8'))\n",
    "    req.add_header('Content-Type', 'application/json')\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "        print (\"Request time cost %f\" % (timer() - begin))\n",
    "    except URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "\n",
    "    if (IS_PY3):\n",
    "        result_str = str(result_str, 'utf-8')\n",
    "    print(result_str)\n",
    "    with open(\"result.txt\",\"w\") as of:\n",
    "        of.write(result_str)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "67b3d1d4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'{\"corpus_no\":\"7230636654441773339\",\"err_msg\":\"success.\",\"err_no\":0,\"result\":[\"北京科技馆。\"],\"sn\":\"325908973431683513785\"}\\n'"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result_str"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "0e788176",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'corpus_no': '7230636654441773339',\n",
       " 'err_msg': 'success.',\n",
       " 'err_no': 0,\n",
       " 'result': ['北京科技馆。'],\n",
       " 'sn': '325908973431683513785'}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# eval 将字符串转换成字典，前提：字符串中是字典\n",
    "eval(result_str)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "42fa6786",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'北京科技馆'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "result_整理 = eval(result_str)['result'][0][:-1]\n",
    "result_整理"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fd263e69",
   "metadata": {},
   "source": [
    "# 2. 创建回复字典"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "0699edd3",
   "metadata": {},
   "outputs": [],
   "source": [
    "qa ={\n",
    "    \"你好\":\"好个啥呀！\"\n",
    "    \"北京科技馆\":\"中国科学技术馆，位于北京市朝阳区北辰东路5号，东临亚运居住区，西濒奥运水系，南依奥运主体育场，北望森林公园，于1958年筹建，建设分为两期工程和新馆工程，分别于1988年9月22日、2000年4月29日、2009年9月16日开放。\"\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "12eaca52",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'中国科学技术馆，位于北京市朝阳区北辰东路5号，东临亚运居住区，西濒奥运水系，南依奥运主体育场，北望森林公园，于1958年筹建，建设分为两期工程和新馆工程，分别于1988年9月22日、2000年4月29日、2009年9月16日开放。'"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "qa.get(result_整理)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61db6406",
   "metadata": {},
   "source": [
    "# 3. 结合1，2步骤"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "7c5fbdec",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "中国科学技术馆，位于北京市朝阳区北辰东路5号，东临亚运居住区，西濒奥运水系，南依奥运主体育场，北望森林公园，于1958年筹建，建设分为两期工程和新馆工程，分别于1988年9月22日、2000年4月29日、2009年9月16日开放。\n"
     ]
    }
   ],
   "source": [
    "# 步骤1\n",
    "if __name__ == '__main__':\n",
    "    token = fetch_token()\n",
    "\n",
    "    speech_data = []\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "\n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "    speech = base64.b64encode(speech_data)\n",
    "    if (IS_PY3):\n",
    "        speech = str(speech, 'utf-8')\n",
    "    params = {'dev_pid': DEV_PID,\n",
    "             #\"lm_id\" : LM_ID,    #测试自训练平台开启此项\n",
    "              'format': FORMAT,\n",
    "              'rate': RATE,\n",
    "              'token': token,\n",
    "              'cuid': CUID,\n",
    "              'channel': 1,\n",
    "              'speech': speech,\n",
    "              'len': length\n",
    "              }\n",
    "    post_data = json.dumps(params, sort_keys=False)\n",
    "    # print post_data\n",
    "    req = Request(ASR_URL, post_data.encode('utf-8'))\n",
    "    req.add_header('Content-Type', 'application/json')\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "#         print (\"Request time cost %f\" % (timer() - begin))\n",
    "    except URLError as err:\n",
    "#         print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "\n",
    "    if (IS_PY3):\n",
    "        result_str = str(result_str, 'utf-8')\n",
    "    # 步骤2\n",
    "#     print(result_str)\n",
    "    result_整理 = eval(result_str)['result'][0][:-1]\n",
    "    print(qa.get(result_整理))\n",
    "    with open(\"result.txt\",\"w\") as of:\n",
    "        of.write(result_str)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9f0e2617",
   "metadata": {},
   "source": [
    "# 4. 语音合成\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "id": "1394f17c",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "fetch token begin\n",
      "{\"refresh_token\":\"25.e8d06fe18f8fe879866339f223722c77.315360000.1998876584.282335-19331335\",\"expires_in\":2592000,\"session_key\":\"9mzdCSZTxPhCqK24NRNXyPUxokQvHoiC5+DWbBWnIlhX8Hg7UEnFqmABAyjpg+kH4O8fLiPQCnmvzLACQUhaNFe9MLhNfA==\",\"access_token\":\"24.20a8c585c424a3cc8605688cac165278.2592000.1686108584.282335-19331335\",\"scope\":\"brain_asr_async brain_speech_realtime audio_voice_assistant_get brain_enhanced_asr audio_tts_post public brain_all_scope picchain_test_picchain_api_scope wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\\u6743\\u9650 vis-classify_flower lpq_\\u5f00\\u653e cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_\\u5f00\\u653eScope vis-ocr_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 idl-video_\\u865a\\u62df\\u4eba\\u7269\\u52a9\\u7406 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx\",\"session_secret\":\"1d2da51929e8a4b37c41893bc06e8b05\"}\n",
      "\n",
      "{'refresh_token': '25.e8d06fe18f8fe879866339f223722c77.315360000.1998876584.282335-19331335', 'expires_in': 2592000, 'session_key': '9mzdCSZTxPhCqK24NRNXyPUxokQvHoiC5+DWbBWnIlhX8Hg7UEnFqmABAyjpg+kH4O8fLiPQCnmvzLACQUhaNFe9MLhNfA==', 'access_token': '24.20a8c585c424a3cc8605688cac165278.2592000.1686108584.282335-19331335', 'scope': 'brain_asr_async brain_speech_realtime audio_voice_assistant_get brain_enhanced_asr audio_tts_post public brain_all_scope picchain_test_picchain_api_scope wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test权限 vis-classify_flower lpq_开放 cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base smartapp_mapp_dev_manage iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_开放Scope vis-ocr_虚拟人物助理 idl-video_虚拟人物助理 smartapp_component smartapp_search_plugin avatar_video_test b2b_tp_openapi b2b_tp_openapi_online smartapp_gov_aladin_to_xcx', 'session_secret': '1d2da51929e8a4b37c41893bc06e8b05'}\n",
      "SUCCESS WITH TOKEN: 24.20a8c585c424a3cc8605688cac165278.2592000.1686108584.282335-19331335 ; EXPIRES IN SECONDS: 2592000\n",
      "%E4%B8%AD%E5%9B%BD%E7%A7%91%E5%AD%A6%E6%8A%80%E6%9C%AF%E9%A6%86%EF%BC%8C%E4%BD%8D%E4%BA%8E%E5%8C%97%E4%BA%AC%E5%B8%82%E6%9C%9D%E9%98%B3%E5%8C%BA%E5%8C%97%E8%BE%B0%E4%B8%9C%E8%B7%AF5%E5%8F%B7%EF%BC%8C%E4%B8%9C%E4%B8%B4%E4%BA%9A%E8%BF%90%E5%B1%85%E4%BD%8F%E5%8C%BA%EF%BC%8C%E8%A5%BF%E6%BF%92%E5%A5%A5%E8%BF%90%E6%B0%B4%E7%B3%BB%EF%BC%8C%E5%8D%97%E4%BE%9D%E5%A5%A5%E8%BF%90%E4%B8%BB%E4%BD%93%E8%82%B2%E5%9C%BA%EF%BC%8C%E5%8C%97%E6%9C%9B%E6%A3%AE%E6%9E%97%E5%85%AC%E5%9B%AD%EF%BC%8C%E4%BA%8E1958%E5%B9%B4%E7%AD%B9%E5%BB%BA%EF%BC%8C%E5%BB%BA%E8%AE%BE%E5%88%86%E4%B8%BA%E4%B8%A4%E6%9C%9F%E5%B7%A5%E7%A8%8B%E5%92%8C%E6%96%B0%E9%A6%86%E5%B7%A5%E7%A8%8B%EF%BC%8C%E5%88%86%E5%88%AB%E4%BA%8E1988%E5%B9%B49%E6%9C%8822%E6%97%A5%E3%80%812000%E5%B9%B44%E6%9C%8829%E6%97%A5%E3%80%812009%E5%B9%B49%E6%9C%8816%E6%97%A5%E5%BC%80%E6%94%BE%E3%80%82\n",
      "test on Web Browserhttp://tsn.baidu.com/text2audio?tok=24.20a8c585c424a3cc8605688cac165278.2592000.1686108584.282335-19331335&tex=%25E4%25B8%25AD%25E5%259B%25BD%25E7%25A7%2591%25E5%25AD%25A6%25E6%258A%2580%25E6%259C%25AF%25E9%25A6%2586%25EF%25BC%258C%25E4%25BD%258D%25E4%25BA%258E%25E5%258C%2597%25E4%25BA%25AC%25E5%25B8%2582%25E6%259C%259D%25E9%2598%25B3%25E5%258C%25BA%25E5%258C%2597%25E8%25BE%25B0%25E4%25B8%259C%25E8%25B7%25AF5%25E5%258F%25B7%25EF%25BC%258C%25E4%25B8%259C%25E4%25B8%25B4%25E4%25BA%259A%25E8%25BF%2590%25E5%25B1%2585%25E4%25BD%258F%25E5%258C%25BA%25EF%25BC%258C%25E8%25A5%25BF%25E6%25BF%2592%25E5%25A5%25A5%25E8%25BF%2590%25E6%25B0%25B4%25E7%25B3%25BB%25EF%25BC%258C%25E5%258D%2597%25E4%25BE%259D%25E5%25A5%25A5%25E8%25BF%2590%25E4%25B8%25BB%25E4%25BD%2593%25E8%2582%25B2%25E5%259C%25BA%25EF%25BC%258C%25E5%258C%2597%25E6%259C%259B%25E6%25A3%25AE%25E6%259E%2597%25E5%2585%25AC%25E5%259B%25AD%25EF%25BC%258C%25E4%25BA%258E1958%25E5%25B9%25B4%25E7%25AD%25B9%25E5%25BB%25BA%25EF%25BC%258C%25E5%25BB%25BA%25E8%25AE%25BE%25E5%2588%2586%25E4%25B8%25BA%25E4%25B8%25A4%25E6%259C%259F%25E5%25B7%25A5%25E7%25A8%258B%25E5%2592%258C%25E6%2596%25B0%25E9%25A6%2586%25E5%25B7%25A5%25E7%25A8%258B%25EF%25BC%258C%25E5%2588%2586%25E5%2588%25AB%25E4%25BA%258E1988%25E5%25B9%25B49%25E6%259C%258822%25E6%2597%25A5%25E3%2580%25812000%25E5%25B9%25B44%25E6%259C%258829%25E6%2597%25A5%25E3%2580%25812009%25E5%25B9%25B49%25E6%259C%258816%25E6%2597%25A5%25E5%25BC%2580%25E6%2594%25BE%25E3%2580%2582&per=1&spd=4&pit=5&vol=5&aue=3&cuid=123456PYTHON&lan=zh&ctp=1\n",
      "result saved as :result.mp3\n"
     ]
    }
   ],
   "source": [
    "# coding=utf-8\n",
    "import sys\n",
    "import json\n",
    "\n",
    "IS_PY3 = sys.version_info.major == 3\n",
    "if IS_PY3:\n",
    "    from urllib.request import urlopen\n",
    "    from urllib.request import Request\n",
    "    from urllib.error import URLError\n",
    "    from urllib.parse import urlencode\n",
    "    from urllib.parse import quote_plus\n",
    "else:\n",
    "    import urllib2\n",
    "    from urllib import quote_plus\n",
    "    from urllib2 import urlopen\n",
    "    from urllib2 import Request\n",
    "    from urllib2 import URLError\n",
    "    from urllib import urlencode\n",
    "\n",
    "\n",
    "\n",
    "TEXT = qa.get(result_整理)\n",
    "\n",
    "# 发音人选择, 基础音库：0为度小美，1为度小宇，3为度逍遥，4为度丫丫，\n",
    "# 精品音库：5为度小娇，103为度米朵，106为度博文，110为度小童，111为度小萌，默认为度小美 \n",
    "PER = 1\n",
    "# 语速，取值0-15，默认为5中语速\n",
    "SPD = 4\n",
    "# 音调，取值0-15，默认为5中语调\n",
    "PIT = 5\n",
    "# 音量，取值0-9，默认为5中音量\n",
    "VOL = 5\n",
    "# 下载的文件格式, 3：mp3(default) 4： pcm-16k 5： pcm-8k 6. wav\n",
    "AUE = 3\n",
    "\n",
    "FORMATS = {3: \"mp3\", 4: \"pcm\", 5: \"pcm\", 6: \"wav\"}\n",
    "FORMAT = FORMATS[AUE]\n",
    "\n",
    "CUID = \"123456PYTHON\"\n",
    "\n",
    "TTS_URL = 'http://tsn.baidu.com/text2audio'\n",
    "\n",
    "\n",
    "class DemoError(Exception):\n",
    "    pass\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN start \"\"\"\n",
    "\n",
    "TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'\n",
    "SCOPE = 'audio_tts_post'  # 有此scope表示有tts能力，没有请在网页里勾选\n",
    "\n",
    "\n",
    "def fetch_token():\n",
    "    print(\"fetch token begin\")\n",
    "    params = {'grant_type': 'client_credentials',\n",
    "              'client_id': API_KEY,\n",
    "              'client_secret': SECRET_KEY}\n",
    "    post_data = urlencode(params)\n",
    "    if (IS_PY3):\n",
    "        post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req, timeout=5)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    if (IS_PY3):\n",
    "        result_str = result_str.decode()\n",
    "\n",
    "    print(result_str)\n",
    "    result = json.loads(result_str)\n",
    "    print(result)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if not SCOPE in result['scope'].split(' '):\n",
    "            raise DemoError('scope is not correct')\n",
    "        print('SUCCESS WITH TOKEN: %s ; EXPIRES IN SECONDS: %s' % (result['access_token'], result['expires_in']))\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "\n",
    "\"\"\"  TOKEN end \"\"\"\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    token = fetch_token()\n",
    "    tex = quote_plus(TEXT)  # 此处TEXT需要两次urlencode\n",
    "    print(tex)\n",
    "    params = {'tok': token, 'tex': tex, 'per': PER, 'spd': SPD, 'pit': PIT, 'vol': VOL, 'aue': AUE, 'cuid': CUID,\n",
    "              'lan': 'zh', 'ctp': 1}  # lan ctp 固定参数\n",
    "\n",
    "    data = urlencode(params)\n",
    "    print('test on Web Browser' + TTS_URL + '?' + data)\n",
    "\n",
    "    req = Request(TTS_URL, data.encode('utf-8'))\n",
    "    has_error = False\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "\n",
    "        headers = dict((name.lower(), value) for name, value in f.headers.items())\n",
    "\n",
    "        has_error = ('content-type' not in headers.keys() or headers['content-type'].find('audio/') < 0)\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "        has_error = True\n",
    "\n",
    "    save_file = \"error.txt\" if has_error else 'result.' + FORMAT\n",
    "    with open(save_file, 'wb') as of:\n",
    "        of.write(result_str)\n",
    "\n",
    "    if has_error:\n",
    "        if (IS_PY3):\n",
    "            result_str = str(result_str, 'utf-8')\n",
    "        print(\"tts api  error:\" + result_str)\n",
    "\n",
    "    print(\"result saved as :\" + save_file)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
